//
//  HMComposePictuerView.swift
//  GuoGuo
//
//  Created by 艾小新 on 16/8/15.
//  Copyright © 2016年 xiaoxin. All rights reserved.
//

import UIKit

class HMComposePictuerView: UICollectionView {

    
    // 记录用户选择的图片
    var images: [UIImage] = [UIImage]()
    
    
    // 单击 + 事件
    var selectedPictureClosure: (()->())?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {

        backgroundColor = UIColor.clearColor()
        // 设置数据源
        dataSource = self
        delegate = self
        // 注册cell
        registerClass(HMComposePictuerCollectionCell.self, forCellWithReuseIdentifier: HMComposePictureViewCellString)
    }
    
    // 如果写在上面，frame就算错了
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let itemMargin: CGFloat = 5
        let itemWH = CGFloat(Int((self.frame.width - 2 * itemMargin) / 3))
        
        // 能够获取到当前控件的最新宽高
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        // 设置条目之前的间距
        layout.minimumInteritemSpacing = itemMargin
        layout.minimumLineSpacing = itemMargin
    }
    
    
    // 配置图片
    func addImage(img:UIImage) {
        // 记录数据
        images.append(img)
        // 刷新数据
        reloadData()
    }

}

private let HMComposePictureViewCellString = "HMComposePictureViewCellString"



// MARK: - cell的数据源方法
extension HMComposePictuerView: UICollectionViewDataSource,UICollectionViewDelegate {
    
    

    
    // 有多少个item
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let count = images.count
        // 如果count == 0 或者 count == 9 就返回 count
        // 否则返回count + 1 (因为需要添加一个加号按钮)
        return (count == 0 || count == 9) ? count : count + 1
        
    }
    

    
    // 这种方法需要注册cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HMComposePictureViewCellString, forIndexPath: indexPath) as! HMComposePictuerCollectionCell
        
        if images.count == indexPath.item {
             cell.image = nil
            
        }else {
             cell.image = images[indexPath.item]
            
            // cell 返回 删除图片事件
             cell.deleteBtnClickCallBack = { [weak self] (deleteCell:HMComposePictuerCollectionCell) in
                
                if let inx = self?.indexPathForCell(deleteCell) {
                    
                    // 移除
                    self?.images.removeAtIndex(inx.item)
                    
                    // 刷洗
                    self?.reloadData()
                }
            }
            
        }
        return cell
    }
    
    // cell的单击事件
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        // 单击事件 如果是 + 号就调用添加上一级控制器的添加按钮
        // 判断是否是加号按钮点击
        if indexPath.item == images.count {
            // 执行闭包
            selectedPictureClosure?()
        }

        
    }
   
}

// MARK: -自定义cell
private class HMComposePictuerCollectionCell: UICollectionViewCell {
    
    var deleteBtnClickCallBack: ((deleteCell: HMComposePictuerCollectionCell)->())?
    
    
    var image: UIImage? {
        
        didSet {
            
            deleteButton.hidden = image == nil
            
            if image == nil {
                // 设置成加号按钮
                imageView.image = UIImage(named: "compose_pic_add")
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
            }else {
                imageView.image = image
                imageView.highlightedImage = image

            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        
        deleteButton.snp_makeConstraints { (make) in
            make.top.trailing.equalTo(imageView)
        }
    }

    // MARK: -懒加载
    private lazy var imageView: UIImageView = {
       
        let imageView = UIImageView()
        imageView.contentMode = .ScaleAspectFill
        imageView.clipsToBounds = true
        return imageView
        
    }()
    
    // 删除按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: #selector(HMComposePictuerCollectionCell.deleteButtonClick(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        button.sizeToFit()
        return button
    }()
    
    @objc func deleteButtonClick(deleteCell:HMComposePictuerCollectionCell) {
        // 删除掉这张图片
        deleteBtnClickCallBack?(deleteCell: self)
    }
    
    
}
